package com.daocao.jy.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.daocao.jy.Application;
import com.daocao.jy.R;
import com.daocao.jy.api.Api;
import com.daocao.jy.base.BaseActivity;
import com.daocao.jy.constant.Const;
import com.daocao.jy.constant.UserInfoGlobal;
import com.daocao.jy.util.CleanMessageUtil;
import com.daocao.jy.util.Dialog;
import com.daocao.jy.util.DownloadUtil;
import com.daocao.jy.util.FileUtils;
import com.daocao.jy.util.Network;
import com.daocao.jy.util.PreferenceUtils;
import com.daocao.jy.util.RxLifeUtil;
import com.daocao.jy.util.ToastUtil;
import com.daocao.jy.util.Util;
import com.daocao.jy.view.LoginDialog;
import com.daocao.jy.view.V19FrameLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class SettingActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_login_logout)
    TextView btnLoginLogout;
    @BindView(R.id.btn_tips_switch)
    ImageView btnTipsSwitch;

    private Unbinder unbiner;
    private DownloadBroadcastReceiver receiver;
    private DownloadChangeObserver downloadObserver;
    private DownloadManager manager;
    private MaterialDialog materialDialog;
    private long lastDownloadId = 0;
    private boolean isShowDialog = false;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    private boolean tipsOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("设置");
        if (UserInfoGlobal.isLogin()) {
            btnLoginLogout.setText("退出当前账号");
        } else {
            btnLoginLogout.setText("登录");
        }
    }

    public void getLogout() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getLogout().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    btnLoginLogout.setText("登录");
                    UserInfoGlobal.logout();
                    ToastUtil.makeText(this, "退出成功");
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_tips_switch, R.id.btn_login_logout, R.id.btn_back, R.id.btn_change_phone, R.id.btn_about, R.id.btn_point, R.id.btn_check_update, R.id.btn_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_login_logout:
                if (UserInfoGlobal.isLogin()) {
                    getLogout();
                } else {
                    new LoginDialog(this).setDialogClickListener(new LoginDialog.DialogDefaultClickListener() {
                        @Override
                        public void loginSuccess() {
                            btnLoginLogout.setText("退出当前账号");
                        }

                        @Override
                        public void cancel() {

                        }
                    }).show();
                }
                break;
            case R.id.btn_tips_switch:
                btnTipsSwitch.setImageResource(tipsOpen ? R.mipmap.img_setting_off : R.mipmap.img_setting_on);
                tipsOpen=!tipsOpen;
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_change_phone:
                Util.startActivity(this, ChangePhoneActivity.class);
                break;
            case R.id.btn_about:
                break;
            case R.id.btn_point:
                break;
            case R.id.btn_check_update:
                Dialog.showDefaultDialog(this, "", "发现新版本，是否更新？", "取消", "立即更新", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
            case R.id.btn_clear:
                Dialog.showDefaultDialog(this, "", "是否确定清除缓存？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {
                        CleanMessageUtil.clearAllCache(Application.getInstance());
                    }
                });
                break;
        }
    }


    /**
     * 检查版本
     */
    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String url = PreferenceUtils.getString(this, "download_url", "");


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {
//                isFirstTips = false;

                //注册下载监听
                receiver = new DownloadBroadcastReceiver();
                registerReceiver(receiver, new IntentFilter(
                        DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                showInstallDialog();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private void showInstallDialog() {
        if (!isShowDialog) {
            isShowDialog = true;
            String updateContent = PreferenceUtils.getString(this, "upgrade_msg", "");
            if (updateContent.contains("{current_version}"))
                updateContent = updateContent.replace("{current_version}", Util.getVersion(this));
            if (updateContent.contains("{lastest_version}"))
                updateContent = updateContent.replace("{lastest_version}", PreferenceUtils.getString(this, "lastest_version", "1.0.0"));
            if (!Util.isWifi(this))
                updateContent = updateContent + ",\n当前网络不在WiFi环境，是否升级？";


//            String leftBtn;
//            if (PreferenceUtils.getInt(this, "forced_upgrade", 0) == 1)
//                leftBtn = "";
//            else leftBtn = "跳过";
            boolean isForce = false;
            if (PreferenceUtils.getInt(this, "forced_upgrade", 0) == 1)
                isForce = true;
            else isForce = false;
            Dialog.showVersionDialog(this, updateContent, isForce, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    isShowDialog = false;
                    if (!canDownloadState()) {
                        Dialog.showDefaultDialog(SettingActivity.this, "提示", "请开启下载服务权限", getResources().getString(R.string.cancel), "前往开启", true, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                String packageName = "com.android.providers.downloads";
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + packageName));
                                startActivity(intent);
                            }

                            @Override
                            public void cancel() {
                                showInstallDialog();
                            }
                        });
                        return;
                    }
                    downloadApp();
                }

                @Override
                public void cancel() {

                }
            });

        }
    }


    private void downloadApp() {
        //判断是否6.0
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        } else {
            initDownloadManager();
        }
    }


    /**
     * 初始化下载
     */
    private void initDownloadManager() {
        String url = PreferenceUtils.getString(this, "download_url", "");
        if (TextUtils.isEmpty(url)) return;

        if (materialDialog == null) {
            materialDialog = new MaterialDialog.Builder(this)
                    .title("版本升级")
                    .content("正在下载安装包，请稍候..")
                    .progress(false, 100, true)
                    .cancelable(false)
                    .show();
        }

        try {
            manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置下载路径和文件名
            request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, Const.APP_NAME);
//            request.setDestinationInExternalPublicDir("download", Const.APP_NAME);

            request.setDescription(getResources().getString(R.string.app_name)
                    + "正在下载安装包，请稍候..");

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setMimeType("application/vnd.android.package-archive");

            // 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();

            // 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            lastDownloadId = manager.enqueue(request);

            // 把当前下载的ID保存起来
            PreferenceUtils.putLong(this, "downloadId", lastDownloadId);

            //采用内容观察者模式实现进度
            downloadObserver = new DownloadChangeObserver(null);
            getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    //用于显示下载进度
    private class DownloadChangeObserver extends ContentObserver {

        private DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                p = p + Util.getRandomNum(5, 15);
                if (progress < 80) {
                    if (p > 80) materialDialog.setProgress(80);
                    else
                        materialDialog.setProgress(p);
                } else
                    materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.setProgress(100);
//                    materialDialog.dismiss();
                }
            }
        }


    }

    private int p = 10;

    /**
     * 下载广播
     */
    public class DownloadBroadcastReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {


            try {
                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                    long myDwonloadID = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                    long refernece = PreferenceUtils.getLong(context, "downloadId", 0);

                    if (refernece == myDwonloadID) {
                        manager = (DownloadManager) context
                                .getSystemService(DOWNLOAD_SERVICE);

//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) installApp();
//                        else
                        DownloadUtil.installApp(SettingActivity.this, myDwonloadID);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取权限回调 兼容6.0
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                initDownloadManager();
            } else {
                // 获取权限失败
                ToastUtil.makeText(this, "获取权限失败~");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (materialDialog != null && materialDialog.isShowing()) {
//            isFirstTips = false;
            return;
        }
        checkUpdate();
    }
}
